"""
Content Management View for Desktop Application
桌面应用内容管理界面
"""

import logging
from typing import Optional, Dict, Any, List
import asyncio

import flet as ft
from flet import (
    Page,
    Container,
    Column,
    Row,
    Text,
    TextField,
    ElevatedButton,
    IconButton,
    Dropdown,
    dropdown,
    Icon,
    Icons,
    Colors,
    Card,
    Divider,
    ListView,
    Image,
    ProgressRing,
    Badge,
    AlertDialog,
    Tabs,
    Tab,
    PopupMenuButton,
    PopupMenuItem,
    Checkbox,
)

from ..services.api_client import APIClient
from ..core.state_manager import StateManager

logger = logging.getLogger(__name__)


class ContentManagementView:
    """内容管理界面视图类"""
    
    def __init__(self, page: Page, state_manager: StateManager, api_client: APIClient):
        self.page = page
        self.state_manager = state_manager
        self.api_client = api_client
        
        # 界面组件
        self.content: Optional[Container] = None
        self.main_column: Optional[Column] = None
        self.content_list_view: Optional[ListView] = None
        
        # 筛选控件
        self.search_field: Optional[TextField] = None
        self.content_type_filter: Optional[Dropdown] = None
        self.status_filter: Optional[Dropdown] = None
        self.sort_dropdown: Optional[Dropdown] = None
        self.view_mode_dropdown: Optional[Dropdown] = None
        
        # 状态
        self.content_list: List[Dict[str, Any]] = []
        self.filtered_content: List[Dict[str, Any]] = []
        self.selected_content: Optional[Dict[str, Any]] = None
        self.is_loading: bool = False
        self.current_page: int = 1
        self.page_size: int = 20
        self.view_mode: str = "grid"  # grid, list
        
    async def show(self) -> None:
        """显示内容管理界面"""
        try:
            logger.info("Showing content management view")
            
            # 创建界面
            await self._create_interface()
            
            # 加载内容列表
            await self.load_content_list()
            
            logger.info("Content management view shown successfully")
            
        except Exception as e:
            logger.error(f"Failed to show content management view: {e}")
            raise
    
    def get_content(self) -> Container:
        """获取界面内容"""
        return self.content
    
    async def _create_interface(self) -> None:
        """创建界面"""
        # 创建筛选工具栏
        filter_toolbar = self._create_filter_toolbar()
        
        # 创建内容列表区域
        content_area = self._create_content_area()
        
        # 创建主列
        self.main_column = Column([
            # 标题区域
            Container(
                content=Column([
                    Text("内容管理", size=28, weight=ft.FontWeight.BOLD),
                    Text(
                        "查看、管理和下载您生成的内容",
                        size=16,
                        color=colors.SECONDARY,
                    ),
                ], spacing=5),
                padding=ft.padding.only(bottom=20),
            ),
            
            # 筛选工具栏
            filter_toolbar,
            
            # 内容区域
            content_area,
        ],
        spacing=20,
        scroll=ft.ScrollMode.AUTO,
        )
        
        # 创建主内容容器
        self.content = Container(
            content=self.main_column,
            padding=20,
            expand=True,
        )
    
    def _create_filter_toolbar(self) -> Container:
        """创建筛选工具栏"""
        # 搜索框
        self.search_field = TextField(
            label="搜索内容",
            hint_text="输入关键词搜索...",
            prefix_icon=icons.SEARCH,
            expand=True,
            on_change=self._on_search_change,
        )
        
        # 内容类型筛选
        self.content_type_filter = Dropdown(
            label="内容类型",
            options=[
                dropdown.Option("all", "全部类型"),
                dropdown.Option("image", "图像"),
                dropdown.Option("video", "视频"),
                dropdown.Option("audio", "音频"),
                dropdown.Option("text", "文本"),
            ],
            value="all",
            width=150,
            on_change=self._on_filter_change,
        )
        
        # 状态筛选
        self.status_filter = Dropdown(
            label="状态",
            options=[
                dropdown.Option("all", "全部状态"),
                dropdown.Option("completed", "已完成"),
                dropdown.Option("processing", "处理中"),
                dropdown.Option("pending", "等待中"),
                dropdown.Option("failed", "失败"),
            ],
            value="all",
            width=150,
            on_change=self._on_filter_change,
        )
        
        # 排序方式
        self.sort_dropdown = Dropdown(
            label="排序方式",
            options=[
                dropdown.Option("created_at_desc", "创建时间（最新）"),
                dropdown.Option("created_at_asc", "创建时间（最早）"),
                dropdown.Option("title_asc", "标题（A-Z）"),
                dropdown.Option("title_desc", "标题（Z-A）"),
                dropdown.Option("file_size_desc", "文件大小（大-小）"),
                dropdown.Option("file_size_asc", "文件大小（小-大）"),
            ],
            value="created_at_desc",
            width=200,
            on_change=self._on_sort_change,
        )
        
        # 视图模式
        self.view_mode_dropdown = Dropdown(
            label="视图模式",
            options=[
                dropdown.Option("grid", "网格视图"),
                dropdown.Option("list", "列表视图"),
            ],
            value=self.view_mode,
            width=120,
            on_change=self._on_view_mode_change,
        )
        
        # 刷新按钮
        refresh_button = IconButton(
            icon=icons.REFRESH,
            tooltip="刷新内容列表",
            on_click=self._on_refresh_click,
        )
        
        return Container(
            content=Column([
                Row([
                    self.search_field,
                    refresh_button,
                ], spacing=10),
                Row([
                    self.content_type_filter,
                    self.status_filter,
                    self.sort_dropdown,
                    self.view_mode_dropdown,
                ], spacing=10, wrap=True),
            ], spacing=15),
            padding=20,
            bgcolor=colors.SURFACE_VARIANT,
            border_radius=8,
        )
    
    def _create_content_area(self) -> Container:
        """创建内容区域"""
        # 创建内容列表视图
        self.content_list_view = ListView(
            spacing=10,
            padding=10,
            expand=True,
        )
        
        return Container(
            content=self.content_list_view,
            padding=10,
            bgcolor=colors.SURFACE,
            border_radius=8,
            expand=True,
        )
    
    # 业务逻辑
    async def load_content_list(self) -> None:
        """加载内容列表"""
        try:
            logger.info("Loading content list")
            self._set_loading_state(True)
            
            # 从状态管理器获取内容列表
            content_list = await self.state_manager.get_content_list()
            
            if not content_list:
                # 从API加载内容
                response = await self.api_client.list_content(
                    page=self.current_page,
                    page_size=self.page_size
                )
                
                if response.get("success"):
                    content_list = response.get("data", {}).get("items", [])
                    await self.state_manager.set_content_list(content_list)
            
            self.content_list = content_list
            self.filtered_content = content_list
            
            # 更新界面显示
            await self._update_content_display()
            
            logger.info(f"Content list loaded: {len(content_list)} items")
            
        except Exception as e:
            logger.error(f"Failed to load content list: {e}")
            self._show_error(f"加载内容列表失败: {e}")
            
        finally:
            self._set_loading_state(False)
    
    async def refresh_content_list(self) -> None:
        """刷新内容列表"""
        await self.load_content_list()
    
    async def _update_content_display(self) -> None:
        """更新内容显示"""
        try:
            self.content_list_view.controls.clear()
            
            if not self.filtered_content:
                # 显示空状态
                empty_state = Container(
                    content=Column([
                        Icon(icons.FOLDER_OPEN, size=64, color=colors.SECONDARY),
                        Text("暂无内容", size=20, weight=ft.FontWeight.BOLD),
                        Text("您还没有生成任何内容，快去创建一些吧！", size=14, color=colors.SECONDARY),
                        ElevatedButton(
                            text="立即创建",
                            icon=icons.ADD_CIRCLE,
                            on_click=lambda _: self._navigate_to_creation(),
                        ),
                    ],
                    spacing=15,
                    horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                    alignment=ft.MainAxisAlignment.CENTER,
                    ),
                    padding=40,
                    alignment=ft.alignment.center,
                )
                self.content_list_view.controls.append(empty_state)
            else:
                # 显示内容列表
                if self.view_mode == "grid":
                    await self._display_grid_view()
                else:
                    await self._display_list_view()
            
            self.page.update()
            
        except Exception as e:
            logger.error(f"Failed to update content display: {e}")
    
    async def _display_grid_view(self) -> None:
        """显示网格视图"""
        # 创建网格布局
        grid = ft.GridView(
            runs_count=4,
            max_extent=300,
            child_aspect_ratio=0.8,
            spacing=15,
            run_spacing=15,
            padding=10,
        )
        
        for content in self.filtered_content:
            grid.controls.append(self._create_content_card(content))
        
        self.content_list_view.controls.append(grid)
    
    async def _display_list_view(self) -> None:
        """显示列表视图"""
        for content in self.filtered_content:
            self.content_list_view.controls.append(self._create_content_list_item(content))
    
    def _create_content_card(self, content: Dict[str, Any]) -> Card:
        """创建内容卡片"""
        content_id = content.get("id", "")
        title = content.get("title", "未命名内容")
        content_type = content.get("content_type", "unknown")
        status = content.get("status", "unknown")
        thumbnail_url = content.get("thumbnail_url", "")
        created_at = content.get("created_at", "")
        file_size = content.get("file_size_readable", "--")
        
        # 状态指示器
        status_color = {
            "completed": colors.GREEN,
            "processing": colors.ORANGE,
            "pending": colors.BLUE,
            "failed": colors.RED,
        }.get(status, colors.GREY)
        
        status_text = {
            "completed": "已完成",
            "processing": "处理中",
            "pending": "等待中",
            "failed": "失败",
        }.get(status, "未知")
        
        # 内容类型图标
        type_icon = {
            "image": icons.IMAGE,
            "video": icons.VIDEO_LIBRARY,
            "audio": icons.AUDIOTRACK,
            "text": icons.TEXT_FIELDS,
        }.get(content_type, icons.HELP_OUTLINE)
        
        return Card(
            content=Container(
                content=Column([
                    # 缩略图
                    Container(
                        content=Image(
                            src=thumbnail_url or "https://via.placeholder.com/300x200",
                            fit=ft.ImageFit.COVER,
                            width=280,
                            height=180,
                            border_radius=8,
                        ) if thumbnail_url else Container(
                            content=Icon(type_icon, size=64, color=colors.PRIMARY),
                            alignment=ft.alignment.center,
                            width=280,
                            height=180,
                            bgcolor=colors.SURFACE_VARIANT,
                            border_radius=8,
                        ),
                        padding=10,
                    ),
                    
                    # 内容信息
                    Container(
                        content=Column([
                            Row([
                                Icon(type_icon, size=20, color=colors.PRIMARY),
                                Text(title, size=16, weight=ft.FontWeight.BOLD, expand=True),
                            ], spacing=5),
                            
                            Row([
                                Badge(
                                    content=Text(status_text, size=12),
                                    bgcolor=status_color,
                                ),
                                Text(f"• {file_size}", size=12, color=colors.SECONDARY),
                            ], spacing=5),
                            
                            Text(
                                f"创建于: {created_at[:10] if created_at else '未知'}",
                                size=12,
                                color=colors.SECONDARY,
                            ),
                        ], spacing=8),
                        padding=ft.padding.symmetric(horizontal=10),
                    ),
                    
                    # 操作按钮
                    Container(
                        content=Row([
                            IconButton(
                                icon=icons.VISIBILITY,
                                tooltip="预览",
                                on_click=lambda e, cid=content_id: self._on_preview_click(cid),
                            ),
                            IconButton(
                                icon=icons.DOWNLOAD,
                                tooltip="下载",
                                on_click=lambda e, cid=content_id: self._on_download_click(cid),
                            ),
                            IconButton(
                                icon=icons.DELETE,
                                tooltip="删除",
                                on_click=lambda e, cid=content_id: self._on_delete_click(cid),
                            ),
                        ], alignment=ft.MainAxisAlignment.SPACE_AROUND),
                        padding=ft.padding.symmetric(horizontal=10, vertical=5),
                    ),
                ], spacing=0),
                padding=10,
            ),
            elevation=2,
        )
    
    def _create_content_list_item(self, content: Dict[str, Any]) -> Container:
        """创建内容列表项"""
        content_id = content.get("id", "")
        title = content.get("title", "未命名内容")
        content_type = content.get("content_type", "unknown")
        status = content.get("status", "unknown")
        created_at = content.get("created_at", "")
        file_size = content.get("file_size_readable", "--")
        
        # 内容类型图标
        type_icon = {
            "image": icons.IMAGE,
            "video": icons.VIDEO_LIBRARY,
            "audio": icons.AUDIOTRACK,
            "text": icons.TEXT_FIELDS,
        }.get(content_type, icons.HELP_OUTLINE)
        
        # 状态颜色
        status_color = {
            "completed": colors.GREEN,
            "processing": colors.ORANGE,
            "pending": colors.BLUE,
            "failed": colors.RED,
        }.get(status, colors.GREY)
        
        return Container(
            content=Row([
                # 类型图标
                Icon(type_icon, size=32, color=colors.PRIMARY),
                
                # 内容信息
                Column([
                    Text(title, size=16, weight=ft.FontWeight.BOLD),
                    Row([
                        Badge(
                            content=Text(status, size=12),
                            bgcolor=status_color,
                        ),
                        Text(f"• {file_size}", size=12, color=colors.SECONDARY),
                        Text(f"• {created_at[:10] if created_at else '未知'}", size=12, color=colors.SECONDARY),
                    ], spacing=5),
                ], expand=True, spacing=5),
                
                # 操作按钮
                Row([
                    IconButton(
                        icon=icons.VISIBILITY,
                        tooltip="预览",
                        on_click=lambda e, cid=content_id: self._on_preview_click(cid),
                    ),
                    IconButton(
                        icon=icons.DOWNLOAD,
                        tooltip="下载",
                        on_click=lambda e, cid=content_id: self._on_download_click(cid),
                    ),
                    IconButton(
                        icon=icons.DELETE,
                        tooltip="删除",
                        on_click=lambda e, cid=content_id: self._on_delete_click(cid),
                    ),
                ], spacing=5),
            ], spacing=15, alignment=ft.MainAxisAlignment.START),
            padding=15,
            bgcolor=colors.SURFACE,
            border_radius=8,
        )
    
    # 事件处理
    async def _on_search_change(self, e) -> None:
        """搜索内容"""
        await self._apply_filters()
    
    async def _on_filter_change(self, e) -> None:
        """筛选条件变更"""
        await self._apply_filters()
    
    async def _on_sort_change(self, e) -> None:
        """排序方式变更"""
        await self._apply_sort()
    
    async def _on_view_mode_change(self, e) -> None:
        """视图模式变更"""
        self.view_mode = e.control.value
        await self._update_content_display()
    
    async def _on_refresh_click(self, e) -> None:
        """刷新按钮点击"""
        await self.refresh_content_list()
    
    async def _on_preview_click(self, content_id: str) -> None:
        """预览按钮点击"""
        try:
            content = await self.api_client.get_content(content_id)
            if content.get("success"):
                # 显示预览对话框
                await self._show_preview_dialog(content.get("data", {}))
            else:
                self._show_error("获取内容详情失败")
                
        except Exception as e:
            logger.error(f"Preview error: {e}")
            self._show_error(f"预览失败: {e}")
    
    async def _on_download_click(self, content_id: str) -> None:
        """下载按钮点击"""
        try:
            # 显示确认对话框
            def confirm_download(confirmed):
                if confirmed:
                    asyncio.create_task(self._perform_download(content_id))
            
            self._show_confirm_dialog(
                title="确认下载",
                content="确定要下载这个内容吗？",
                on_confirm=confirm_download
            )
            
        except Exception as e:
            logger.error(f"Download click error: {e}")
            self._show_error(f"下载失败: {e}")
    
    async def _on_delete_click(self, content_id: str) -> None:
        """删除按钮点击"""
        try:
            # 显示确认对话框
            def confirm_delete(confirmed):
                if confirmed:
                    asyncio.create_task(self._perform_delete(content_id))
            
            self._show_confirm_dialog(
                title="确认删除",
                content="确定要删除这个内容吗？此操作无法撤销。",
                on_confirm=confirm_delete
            )
            
        except Exception as e:
            logger.error(f"Delete click error: {e}")
            self._show_error(f"删除失败: {e}")
    
    def _navigate_to_creation(self) -> None:
        """导航到创建页面"""
        # 这里应该导航到内容创建界面
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text("正在跳转到内容创建页面..."),
                duration=2000,
            )
        )
    
    # 业务逻辑
    async def _apply_filters(self) -> None:
        """应用筛选条件"""
        try:
            search_term = self.search_field.value.lower() if self.search_field else ""
            content_type = self.content_type_filter.value if self.content_type_filter else "all"
            status = self.status_filter.value if self.status_filter else "all"
            
            filtered = self.content_list
            
            # 搜索筛选
            if search_term:
                filtered = [
                    content for content in filtered
                    if search_term in content.get("title", "").lower() or
                       search_term in content.get("description", "").lower() or
                       search_term in content.get("prompt", "").lower()
                ]
            
            # 内容类型筛选
            if content_type != "all":
                filtered = [
                    content for content in filtered
                    if content.get("content_type") == content_type
                ]
            
            # 状态筛选
            if status != "all":
                filtered = [
                    content for content in filtered
                    if content.get("status") == status
                ]
            
            self.filtered_content = filtered
            await self._apply_sort()
            
        except Exception as e:
            logger.error(f"Filter application error: {e}")
    
    async def _apply_sort(self) -> None:
        """应用排序"""
        try:
            sort_option = self.sort_dropdown.value if self.sort_dropdown else "created_at_desc"
            
            if sort_option == "created_at_desc":
                self.filtered_content.sort(key=lambda x: x.get("created_at", ""), reverse=True)
            elif sort_option == "created_at_asc":
                self.filtered_content.sort(key=lambda x: x.get("created_at", ""))
            elif sort_option == "title_asc":
                self.filtered_content.sort(key=lambda x: x.get("title", ""))
            elif sort_option == "title_desc":
                self.filtered_content.sort(key=lambda x: x.get("title", ""), reverse=True)
            elif sort_option == "file_size_desc":
                self.filtered_content.sort(key=lambda x: x.get("file_size_bytes", 0), reverse=True)
            elif sort_option == "file_size_asc":
                self.filtered_content.sort(key=lambda x: x.get("file_size_bytes", 0))
            
            await self._update_content_display()
            
        except Exception as e:
            logger.error(f"Sort application error: {e}")
    
    async def _perform_download(self, content_id: str) -> None:
        """执行下载操作"""
        try:
            logger.info(f"Downloading content: {content_id}")
            
            response = await self.api_client.download_content(content_id)
            
            if response.get("success"):
                download_url = response.get("data", {}).get("download_url")
                file_name = response.get("data", {}).get("file_name")
                
                if download_url and file_name:
                    # 这里应该实现实际的文件下载
                    # 由于Flet的限制，我们可以显示下载链接或调用系统下载
                    self._show_success(f"下载链接已生成: {file_name}")
                    
                    # 在实际应用中，这里可以：
                    # 1. 打开系统浏览器下载
                    # 2. 使用后台下载服务
                    # 3. 显示下载链接供用户复制
                    
                else:
                    self._show_error("下载信息不完整")
            else:
                error_message = response.get("error", {}).get("message", "下载失败")
                self._show_error(f"下载失败: {error_message}")
                
        except Exception as e:
            logger.error(f"Download error: {e}")
            self._show_error(f"下载失败: {str(e)}")
    
    async def _perform_delete(self, content_id: str) -> None:
        """执行删除操作"""
        try:
            logger.info(f"Deleting content: {content_id}")
            
            response = await self.api_client.delete_content(content_id)
            
            if response.get("success"):
                # 从状态管理器中移除
                await self.state_manager.remove_content(content_id)
                
                # 刷新列表
                await self.refresh_content_list()
                
                self._show_success("内容删除成功")
            else:
                error_message = response.get("error", {}).get("message", "删除失败")
                self._show_error(f"删除失败: {error_message}")
                
        except Exception as e:
            logger.error(f"Delete error: {e}")
            self._show_error(f"删除失败: {str(e)}")
    
    async def _show_preview_dialog(self, content_data: Dict[str, Any]) -> None:
        """显示预览对话框"""
        # TODO: 实现预览对话框
        self._show_info("预览功能开发中...")
    
    def _show_confirm_dialog(self, title: str, content: str, on_confirm: callable) -> None:
        """显示确认对话框"""
        def handle_confirm(e):
            dialog.open = False
            self.page.update()
            on_confirm(True)
        
        def handle_cancel(e):
            dialog.open = False
            self.page.update()
            on_confirm(False)
        
        dialog = AlertDialog(
            title=Text(title),
            content=Text(content),
            actions=[
                TextButton("取消", on_click=handle_cancel),
                TextButton("确定", on_click=handle_confirm),
            ],
            actions_alignment=ft.MainAxisAlignment.END,
        )
        
        self.page.dialog = dialog
        dialog.open = True
        self.page.update()
    
    # UI辅助方法
    def _set_loading_state(self, is_loading: bool) -> None:
        """设置加载状态"""
        self.is_loading = is_loading
        
        # 禁用/启用控件
        controls = [
            self.search_field,
            self.content_type_filter,
            self.status_filter,
            self.sort_dropdown,
            self.view_mode_dropdown,
        ]
        
        for control in controls:
            if control:
                control.disabled = is_loading
        
        if is_loading:
            # 显示加载指示器
            loading_indicator = Container(
                content=ProgressRing(),
                alignment=ft.alignment.center,
                padding=40,
            )
            self.content_list_view.controls.insert(0, loading_indicator)
        else:
            # 移除加载指示器
            if self.content_list_view.controls and isinstance(self.content_list_view.controls[0], Container):
                if isinstance(self.content_list_view.controls[0].content, ProgressRing):
                    self.content_list_view.controls.pop(0)
        
        self.page.update()
    
    def _show_error(self, message: str) -> None:
        """显示错误消息"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(message, color=colors.ERROR),
                bgcolor=colors.ERROR_CONTAINER,
                duration=4000,
            )
        )
    
    def _show_success(self, message: str) -> None:
        """显示成功消息"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(message, color=colors.GREEN),
                bgcolor=colors.GREEN_CONTAINER,
                duration=3000,
            )
        )
    
    def _show_info(self, message: str) -> None:
        """显示信息消息"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(message),
                duration=2000,
            )
        )